import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/launch_util.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/mine/address_manage.dart';
import 'package:gzmall_app/mine/order_details.dart';
import 'package:gzmall_app/model/coupon.dart';
import 'package:gzmall_app/model/shopping_cart.dart';
import 'package:gzmall_app/model/order_item.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/model/address.dart';
import 'package:flutter_statusbar_manager/flutter_statusbar_manager.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:gzmall_app/shoppping_cart/buy_success.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:gzmall_app/model/wechat_pay_info.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:gzmall_app/model/confirm_order.dart';
import 'package:gzmall_app/model/confirm_order_item.dart';
import 'package:gzmall_app/model/confirm_order_data.dart';

class ConfirmOrderPage extends StatefulWidget {
  List<ShoppingCart> shoppingCartList = [];
  int skuId = 0;
  int quantity = 0;

  ConfirmOrderPage({this.shoppingCartList, this.skuId, this.quantity});
  @override
  State<StatefulWidget> createState() =>
      ConfirmOrderPageState(this.shoppingCartList, this.skuId, this.quantity);
}

class ConfirmOrderPageState extends State<ConfirmOrderPage> {
  List<ShoppingCart> shoppingCartList = [];
  int skuId = 0;
  int quantity = 0;

  Address _defaultAddress;

  List<String> _orderIds = [];
  bool _needExpress = true;
  var _orderItemIds = [];
  var _couponIds = [];

  List<ConfirmOrder> _confirmOrderList = [];
  ConfirmOrderData _confirmOrderData;

  Map<String, Map<String, String>> _selectCoupon = {};

  TextEditingController _contentController = TextEditingController();
  String _content = '';

  ConfirmOrderPageState(this.shoppingCartList, this.skuId, this.quantity);

  @override
  void initState() {
    super.initState();
    if (Platform.isIOS) {
      FlutterStatusbarManager.setStyle(StatusBarStyle.DARK_CONTENT);
    }
    fluwx.registerWxApi(appId: Api.wxAppId);
    fluwx.weChatResponseEventHandler.listen((data) {
      if (data is fluwx.WeChatPaymentResponse) {
        print("<fluwx> fluwx.weChatResponseEventHandler.listen");
        print("<fluwx> data.type " + data.type.toString());
        print("<fluwx> data.errCode " + data.errCode.toString());
        print("<fluwx> data.extData " + data.extData.toString());

        if (data != null && data.errCode != null) {
          switch (data.errCode) {
            case 0:
              // 成功 展示成功页面
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return new BuySuccessPage(
                    _confirmOrderData != null &&
                            _confirmOrderData.totalFee != null
                        ? _confirmOrderData.totalFee.toString()
                        : "0.0",
                    _orderIds[0]);
              })).then((value) {
                Navigator.of(context).pop(true);
                Navigator.of(context).pop();
              });
              break;
            case -1:
              // 错误 可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
              ToastUtil.showMessageToast(data.errStr ?? "微信支付错误");
              break;
            case -2:
              // 用户取消 无需处理。发生场景：用户不支付了，点击取消，返回APP。
              break;
          }
        }
      }
    });

    Future.delayed(Duration.zero, () {
      _initOrderData();
      _getAddresses();
    });
  }

  @override
  void dispose() {
    if (Platform.isIOS) {
      FlutterStatusbarManager.setStyle(StatusBarStyle.LIGHT_CONTENT);
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (Platform.isIOS) {
      FlutterStatusbarManager.setStyle(StatusBarStyle.DARK_CONTENT);
    }
    return Theme(
      data: Theme.of(context).copyWith(
        primaryColor: Colors.white,
      ),
      child: Scaffold(
        appBar: _createAppBar(),
        body: Container(
          color: ColorCommon.grey2,
          child: Column(children: <Widget>[
            Expanded(
              child: ListView.builder(
                itemCount:
                    (_confirmOrderList != null ? _confirmOrderList.length : 0) +
                        2,
                itemBuilder: (BuildContext context, int index) {
                  if (index == 0) {
                    return _createAddressView();
                  } else if (index ==
                      (_confirmOrderList != null
                              ? _confirmOrderList.length
                              : 0) +
                          1) {
                    return InkWell(
                      onTap: () {
                        if (_orderIds != null && _orderIds.length > 0) {
                          return;
                        }
                        _showExpress(context);
                      },
                      child: Container(
                        color: Colors.white,
                        margin: const EdgeInsets.only(top: 10.0, bottom: 50.0),
                        padding: const EdgeInsets.all(10.0),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text("配送方式"),
                            ),
                            Text(_needExpress ? "快递 免邮" : "到店自提"),
                            Image.asset(
                              "images/right_arrow.png",
                              width: 10.0,
                              height: 10.0,
                            ),
                          ],
                        ),
                      ),
                    );
                  } else {
                    return _createShopItem(_confirmOrderList[index - 1]);
                  }
                },
              ),
            ),
            _createBottomBar(),
          ]),
        ),
      ),
    );
  }

  _initOrderData() {
    if (skuId != null && skuId > 0 && quantity != null && quantity > 0) {
      // _addShopCart(skuId, quantity);
    } else {
      _orderItemIds.clear();
      if (shoppingCartList != null && shoppingCartList.length > 0) {
        for (var item in shoppingCartList) {
          if (item.orderItems != null && item.orderItems.length > 0) {
            for (var i in item.orderItems) {
              _orderItemIds.add(i.id);
            }
          }
        }
      }
    }
    _updateOrderData();
  }

  _updateOrderData() {
    _couponIds.clear();
    for (Map<String, String> v in _selectCoupon.values) {
      _couponIds.add(v["id"]);
    }
    _newOrder(_defaultAddress != null ? _defaultAddress.id.toString() : '',
        _needExpress, _couponIds,
        orderItemIds: _orderItemIds,
        skuId: this.skuId,
        quantity: this.quantity);
  }

  _createAppBar() {
    return AppBar(
      elevation: 0.0,
      title: Text(
        "确认订单",
        style: TextStyle(color: Colors.black),
      ),
      leading: IconButton(
        icon: Icon(
          Icons.arrow_back_ios,
          color: Colors.black,
        ),
        onPressed: () {
          if (_orderIds != null && _orderIds.length > 0) {
            _showCancelPayDialog();
            return;
          }
          Navigator.of(context).pop();
        },
      ),
    );
  }

  _createBottomBar() {
    return Container(
      color: Colors.white,
      margin: const EdgeInsets.only(top: 1.0),
      child: Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
        Text(
          "合计金额:",
          style: TextStyle(fontSize: 14.0, color: ColorCommon.black1),
        ),
        Padding(
          padding: const EdgeInsets.only(left: 10.0, right: 10.0),
          child: Text(
            "¥" +
                (_confirmOrderData != null && _confirmOrderData.totalFee != null
                    ? _confirmOrderData.totalFee.toString()
                    : "0.0"),
            style: TextStyle(fontSize: 16.0, color: ColorCommon.primaryColor),
          ),
        ),
        Builder(
          builder: (BuildContext context) => InkWell(
            onTap: () {
              if (_defaultAddress != null) {
                if (_orderIds != null && _orderIds.length > 0) {
                  _showPayWay(context);
                } else {
                  _confirmOrder(
                      _defaultAddress != null
                          ? _defaultAddress.id.toString()
                          : '',
                      _needExpress,
                      _couponIds,
                      orderItemIds: _orderItemIds,
                      skuId: this.skuId,
                      quantity: this.quantity);
                }
              } else {
                ToastUtil.showMessageToast("请选择送货地址");
              }
            },
            child: Container(
              color: ColorCommon.primaryColor,
              height: 50.0,
              alignment: Alignment.center,
              padding: const EdgeInsets.only(left: 25.0, right: 25.0),
              child: Text(
                "提交订单",
                style: TextStyle(fontSize: 16.0, color: Colors.white),
              ),
            ),
          ),
        ),
      ]),
    );
  }

  Widget _createAddressView() {
    return InkWell(
      onTap: () {
        Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
          return new AddressManagePage(
            true,
          );
        })).then((value) {
          if (!mounted) return;
          setState(() {
            _defaultAddress = value;
            _updateOrderData();
          });
        });
      },
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.all(10.0),
        margin: const EdgeInsets.only(top: 1.0, bottom: 1.0),
        child: Row(children: <Widget>[
          Expanded(
            child: _defaultAddress != null
                ? Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                        Row(children: <Widget>[
                          Expanded(
                            child: Text("收货人: " + _defaultAddress.sendee),
                          ),
                          Text(_defaultAddress.phone),
                        ]),
                        Text("收货地址: " +
                            _defaultAddress.province +
                            _defaultAddress.city +
                            _defaultAddress.district +
                            _defaultAddress.address),
                      ])
                : Text("请选择送货地址"),
          ),
          Image.asset(
            "images/right_arrow.png",
            width: 10.0,
            height: 10.0,
          ),
        ]),
      ),
    );
  }

  Widget _createShopItem(ConfirmOrder sc) {
    List<Widget> _items = [];
    if (sc != null && sc.orderItems != null && sc.orderItems.length > 0) {
      _items = sc.orderItems.map((i) {
        return _createShoppingCartGoodsItem(i);
      }).toList();
    } else {
      _items.add(Container());
    }

    return Container(
      margin: const EdgeInsets.only(bottom: 15.0),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <
          Widget>[
        Container(
          padding: const EdgeInsets.all(10.0),
          color: Colors.white,
          child: Row(
            children: <Widget>[
              Text(sc != null && sc.shopName != null ? sc.shopName : ""),
            ],
          ),
        ),
        Container(
          color: Colors.white,
          child: Column(
            children: _items,
          ),
        ),
        sc.coupons != null && sc.coupons.length > 0
            ? InkWell(
                onTap: () {
                  if (_orderIds != null && _orderIds.length > 0) {
                    return;
                  }
                  _showProductCoupons(context, sc.coupons, sc.shopId);
                },
                child: Container(
                  color: Colors.white,
                  padding: const EdgeInsets.all(10.0),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Text("优惠券"),
                      ),
                      Text(_selectCoupon != null &&
                              _selectCoupon[sc.shopId.toString()] != null
                          ? _selectCoupon[sc.shopId.toString()]['name']
                          : "请选择"),
                      Image.asset(
                        "images/right_arrow.png",
                        width: 10.0,
                        height: 10.0,
                      ),
                    ],
                  ),
                ),
              )
            : Container(),
        Container(
          color: Colors.white,
          margin: const EdgeInsets.only(top: 1.0, bottom: 1.0),
          padding: const EdgeInsets.all(10.0),
          child: Row(children: <Widget>[
            Text("买家留言:"),
            Expanded(
              child: Container(
                margin: const EdgeInsets.only(left: 15.0),
                child: TextField(
                  controller: _contentController,
                  style: TextStyle(color: ColorCommon.black1),
                  decoration: InputDecoration.collapsed(
                    hintText: "选填:填写内容和卖家协商确定",
                    hintStyle:
                        TextStyle(fontSize: 14.0, color: ColorCommon.grey1),
                  ),
                  onChanged: (str) {
                    _content = str ?? '';
                  },
                ),
              ),
            ),
          ]),
        ),
        Container(
          padding: const EdgeInsets.all(10.0),
          color: Colors.white,
          child:
              Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
            Text("运费:"),
            Container(
              margin: const EdgeInsets.only(left: 15.0),
              child: Text(
                "¥" +
                    (sc != null && sc.totalFee != null
                        ? sc.expressFee.toString()
                        : "0.0"),
                style: TextStyle(fontSize: 16.0, color: ColorCommon.black1),
              ),
            ),
          ]),
        ),
        Container(
          margin: const EdgeInsets.only(top: 1.0, bottom: 1.0),
          padding: const EdgeInsets.all(10.0),
          color: Colors.white,
          child:
              Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
            Text("优惠:"),
            Container(
              margin: const EdgeInsets.only(left: 15.0),
              child: Text(
                "¥-" +
                    (sc != null && sc.totalFee != null
                        ? sc.couponFee.toString()
                        : "0.0"),
                style: TextStyle(fontSize: 16.0, color: ColorCommon.black1),
              ),
            ),
          ]),
        ),
        Container(
          padding: const EdgeInsets.all(10.0),
          color: Colors.white,
          child:
              Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
            Text("共" +
                (sc != null && sc.totalQuantity != null
                    ? sc.totalQuantity.toString()
                    : "0") +
                "件商品  小计:"),
            Container(
              margin: const EdgeInsets.only(left: 15.0),
              child: Text(
                "¥" +
                    (sc != null && sc.totalFee != null
                        ? sc.totalFee.toString()
                        : "0.0"),
                style:
                    TextStyle(fontSize: 18.0, color: ColorCommon.primaryColor),
              ),
            ),
          ]),
        ),
      ]),
    );
  }

  Widget _createShoppingCartGoodsItem(ConfirmOrderItem item) {
    return Container(
      color: ColorCommon.grey2,
      margin: const EdgeInsets.only(bottom: 4.0),
      padding: const EdgeInsets.only(
          left: 15.0, right: 15.0, top: 10.0, bottom: 10.0),
      child:
          Row(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
        item != null && item.spuAvatar != null
            ? CachedNetworkImage(
                imageUrl: item.spuAvatar,
                fit: BoxFit.fill,
                width: 80.0,
                height: 80.0,
              )
            : Container(color: Colors.grey, width: 80.0, height: 80.0),
        Expanded(
          child: Container(
            margin: const EdgeInsets.only(left: 20.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  item != null && item.spuName != null ? item.spuName : "",
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 16.0, color: ColorCommon.black1),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 2.0),
                  child: Text(
                    item != null && item.sku != null ? item.sku : "",
                    style: TextStyle(fontSize: 14.0, color: ColorCommon.grey3),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 8.0),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Text(
                          "¥" + (item != null ? item.salePrice.toString() : ""),
                          style: TextStyle(
                              fontSize: 18.0, color: ColorCommon.primaryColor),
                        ),
                      ),
                      Text("x" + (item.quantity.toString())),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ]),
    );
  }

  _showPayWay(BuildContext context) {
    Future bottomSheet = showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(15.0),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Stack(
                alignment: FractionalOffset(0.98, 0.5),
                children: <Widget>[
                  Container(
                    width: double.infinity,
                    alignment: Alignment.center,
                    child: Text(
                      "确认付款",
                      textAlign: TextAlign.center,
                      style:
                          TextStyle(fontSize: 16.0, color: ColorCommon.black1),
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      Navigator.of(context).pop(false);
                    },
                    child: Text(
                      "取消",
                      style:
                          TextStyle(fontSize: 16.0, color: ColorCommon.black1),
                    ),
                  ),
                ],
              ),
              Align(
                alignment: Alignment.center,
                child: Padding(
                  padding: const EdgeInsets.only(top: 20.0, bottom: 20.0),
                  child: Text(
                    "¥ " +
                        (_confirmOrderData != null &&
                                _confirmOrderData.totalFee != null
                            ? _confirmOrderData.totalFee.toString()
                            : "0.0"),
                    style: TextStyle(
                      fontSize: 36.0,
                      color: ColorCommon.primaryColor,
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(bottom: 10.0),
                child: Text(
                  "付款方式",
                  style: TextStyle(fontSize: 15.0, color: ColorCommon.black1),
                ),
              ),
              Expanded(
                child: ListView(
                  padding: const EdgeInsets.only(top: 0.0),
                  children: <Widget>[
                    InkWell(
                      onTap: () {
                        _showConfirmPayDialog('确定使用钱包支付?', () {
                          Navigator.of(context).pop();
                        }, () {
                          Navigator.of(context).pop();
                          if (_orderIds != null && _orderIds.length > 0) {
                            _getPayInfo(_orderIds, "moneybag");
                          } else {
                            ToastUtil.showMessageToast("下单错误, 请重试");
                            Navigator.of(context).pop(true);
                          }
                        });
                      },
                      child: Container(
                        color: ColorCommon.grey5,
                        padding: const EdgeInsets.only(
                            left: 15.0, right: 15.0, bottom: 10.0, top: 10.0),
                        margin: const EdgeInsets.only(bottom: 10.0),
                        child: Row(children: <Widget>[
                          Image.asset(
                            "images/money_bag.png",
                            width: 30.0,
                            height: 30.0,
                          ),
                          Padding(
                            padding:
                                const EdgeInsets.only(left: 10.0, right: 10.0),
                            child: Text(
                              "钱包支付",
                              style: TextStyle(
                                  fontSize: 15.0, color: ColorCommon.black1),
                            ),
                          )
                        ]),
                      ),
                    ),
                    LaunchUtil.isInstallWeixin && !SettingUtil.isAppStoreAudit()
                        ? InkWell(
                            onTap: () {
                              if (_orderIds != null && _orderIds.length > 0) {
                                _getPayInfo(_orderIds, "wepay");
                              } else {
                                ToastUtil.showMessageToast("下单错误, 请重试");
                                Navigator.of(context).pop(true);
                              }
                            },
                            child: Container(
                              color: ColorCommon.grey5,
                              padding: const EdgeInsets.only(
                                  left: 15.0,
                                  right: 15.0,
                                  bottom: 10.0,
                                  top: 10.0),
                              margin: const EdgeInsets.only(bottom: 10.0),
                              child: Row(children: <Widget>[
                                Image.asset(
                                  "images/wechat.png",
                                  width: 30.0,
                                  height: 30.0,
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(
                                      left: 10.0, right: 10.0),
                                  child: Text(
                                    "微信支付",
                                    style: TextStyle(
                                        fontSize: 15.0,
                                        color: ColorCommon.black1),
                                  ),
                                )
                              ]),
                            ),
                          )
                        : Container(),
                    LaunchUtil.isInstallAlipay && !SettingUtil.isAppStoreAudit()
                        ? InkWell(
                            onTap: () {
                              if (_orderIds != null && _orderIds.length > 0) {
                                _getPayInfo(_orderIds, "alipay");
                              } else {
                                ToastUtil.showMessageToast("下单错误, 请重试");
                                Navigator.of(context).pop(true);
                              }
                            },
                            child: Container(
                              color: ColorCommon.grey5,
                              padding: const EdgeInsets.only(
                                  left: 15.0,
                                  right: 15.0,
                                  bottom: 10.0,
                                  top: 10.0),
                              margin: const EdgeInsets.only(bottom: 10.0),
                              child: Row(children: <Widget>[
                                Image.asset(
                                  "images/alipay.png",
                                  width: 30.0,
                                  height: 30.0,
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(
                                      left: 10.0, right: 10.0),
                                  child: Text(
                                    "支付宝",
                                    style: TextStyle(
                                        fontSize: 15.0,
                                        color: ColorCommon.black1),
                                  ),
                                ),
                              ]),
                            ),
                          )
                        : Container()
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
    bottomSheet.then((v) {
      if (v != null && !v) {
        _showCancelPayDialog();
      }
    });
  }

  _showExpress(BuildContext context) {
    List<Widget> ws = [
      _getExpressItem("到店自提", () {
        if (!mounted) return;
        setState(() {
          _needExpress = false;
          _updateOrderData();
          Navigator.of(context).pop();
        });
      }),
      _getExpressItem("快递 免邮", () {
        if (!mounted) return;
        setState(() {
          _needExpress = true;
          _updateOrderData();
          Navigator.of(context).pop();
        });
      })
    ];
    Future bottomSheet = showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(15.0),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(bottom: 15.0),
                child: Text(
                  "配送方式",
                  style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
                ),
              ),
              Expanded(
                child: ListView(
                  children: ws,
                ),
              ),
            ],
          ),
        );
      },
    );
    bottomSheet.then((v) {});
  }

  Widget _getExpressItem(String express, Function onTap) {
    return InkWell(
        onTap: onTap,
        child: Container(
          margin: const EdgeInsets.all(10.0),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Text(express),
              ),
              Image.asset(
                "images/right_arrow.png",
                width: 10.0,
                height: 10.0,
              ),
            ],
          ),
        ));
  }

  _showProductCoupons(BuildContext context, List<Coupon> coupons, int shopId) {
    List<Widget> ws;
    if (coupons != null && coupons.length > 0) {
      ws = coupons.map((item) => _getProductCouponItem(item, shopId)).toList();
    } else {
      ws = [];
      ws.add(Align(
          alignment: Alignment.topLeft,
          child: Text(
            "无",
            style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
          )));
    }
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(15.0),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(bottom: 15.0),
                child: Text(
                  "优惠券",
                  style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
                ),
              ),
              Expanded(
                child: ListView(
                  children: ws,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _getProductCouponItem(Coupon coupon, int shopId) {
    return InkWell(
        onTap: () {
          if (!mounted) return;
          setState(() {
            _selectCoupon[shopId.toString()] = {
              'id': coupon.id.toString(),
              'name': coupon.name
            };
            _updateOrderData();
            Navigator.of(context).pop();
          });
        },
        child: Container(
            margin: const EdgeInsets.only(top: 5.0, bottom: 5.0),
            padding: const EdgeInsets.all(10.0),
            decoration: BoxDecoration(
                color: Colors.yellow,
                borderRadius: BorderRadius.all(Radius.circular(5.0))),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Expanded(
                    child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: <Widget>[
                        Text(
                          "¥",
                          style:
                              TextStyle(color: Colors.orange, fontSize: 12.0),
                        ),
                        Text(
                          coupon.money ?? "",
                          style:
                              TextStyle(color: Colors.orange, fontSize: 18.0),
                        ),
                        Text(
                          coupon.name ?? "",
                          style:
                              TextStyle(color: Colors.orange, fontSize: 12.0),
                        ),
                      ],
                    ),
                    Text(
                      coupon.remark ?? "",
                      style: TextStyle(color: Colors.orange, fontSize: 12.0),
                    ),
                    Text(
                      "有效期: " +
                          (coupon.startAt ?? "") +
                          "-" +
                          (coupon.endAt ?? ""),
                      style: TextStyle(color: Colors.orange, fontSize: 12.0),
                    ),
                  ],
                )),
                Text(
                  "选择",
                  style: TextStyle(color: Colors.orange, fontSize: 16.0),
                ),
              ],
            )));
  }

  _showCancelPayDialog() {
    Future dialog = showDialog(
      context: context,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          title: Text("提醒"),
          content: Padding(
            padding: const EdgeInsets.only(top: 10.0),
            child: Text("确定是否取消支付?"),
          ),
          actions: <Widget>[
            CupertinoDialogAction(
              child: Text("去意已决"),
              onPressed: () {
                Navigator.of(context).pop(false);
                Navigator.of(context).pop();
              },
            ),
            CupertinoDialogAction(
              child: Text("重新支付"),
              onPressed: () {
                Navigator.of(context).pop(true);
                _showPayWay(context);
              },
            ),
          ],
        );
      },
    );
    dialog.then((v) {
      if (v == null) {
        _showCancelPayDialog();
      }
    });
  }

  _showConfirmPayDialog(String text, Function onCancel, Function onConfirm) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          title: Text("提醒"),
          content: Padding(
            padding: const EdgeInsets.only(top: 10.0),
            child: Text(text),
          ),
          actions: <Widget>[
            CupertinoDialogAction(
              child: Text("取消"),
              onPressed: () {
                if (onCancel != null) {
                  onCancel();
                }
              },
            ),
            CupertinoDialogAction(
              child: Text("支付"),
              onPressed: () {
                if (onConfirm != null) {
                  onConfirm();
                }
              },
            ),
          ],
        );
      },
    );
  }

  _getAddresses() {
    NetUtil.get(
      context,
      Api.addresses,
      (data, message) {
        List<Address> _addressList = (data as List)
            ?.map((e) => e == null ? null : Address.fromJson(e))
            ?.toList();
        for (var a in _addressList) {
          if (a.isDefault) {
            if (!mounted) return;
            setState(() {
              _defaultAddress = a;
              _updateOrderData();
            });
            break;
          }
        }
      },
    );
  }

  // _addShopCart(int skuId, int quantity) {
  //   Map<String, String> params = {
  //     "sku_id": skuId.toString(),
  //     "quantity": quantity.toString(),
  //   };

  //   NetUtil.post(context, Api.orderItems, (data, message) {
  //     ToastUtil.showToast(message);
  //     _orderItemIds.clear();
  //     if (data != null && data["id"] != null) {
  //       _orderItemIds.add(data["id"] as int);
  //       _updateOrderData();
  //     }
  //   }, params: params, isShowLoading: true);
  // }

  _confirmOrder(String addressId, bool needExpress, var couponIds,
      {var orderItemIds, int skuId, int quantity}) {
    Map<String, Object> params = {
      "coupon_ids": couponIds.join(","),
      "address_id": addressId,
      "need_express": needExpress,
    };
    if (orderItemIds != null && orderItemIds.length > 0) {
      params["order_item_ids"] = orderItemIds.join(",");
    } else {
      params["sku_id"] = skuId;
      params["quantity"] = quantity;
    }

    NetUtil.post(context, Api.orders, (data, message) {
      ToastUtil.showMessageToast(message);

      _orderIds =
          (data as List)?.map((e) => e == null ? null : e.toString())?.toList();

      _showPayWay(context);
    }, params: params, isShowLoading: true);
  }

  _getPayInfo(List<String> orderIds, String payMethod) async {
    Map<String, Object> params = {
      "orders": orderIds.join(","),
      "pay_method": payMethod,
    };

    NetUtil.post(context, Api.pay, (data, message) {
      ToastUtil.showMessageToast(message);

      if (payMethod == "wepay") {
        // 微信支付
        WechatPayInfo wechatPayInfo = WechatPayInfo.fromJson(data);
        fluwx
            .payWithWeChat(
                appId: wechatPayInfo.appid,
                partnerId: wechatPayInfo.partnerid,
                prepayId: wechatPayInfo.prepayid,
                packageValue: wechatPayInfo.package,
                nonceStr: wechatPayInfo.noncestr,
                timeStamp: int.parse(wechatPayInfo.timestamp),
                sign: wechatPayInfo.sign)
            .then((value) {
          print("<fluwx> then(value) ${value}");
        });
      } else if (payMethod == "alipay") {
        // 支付宝支付
        _callAlipay(data);
      } else if (payMethod == "moneybag") {
        Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
          return new BuySuccessPage(
              _confirmOrderData != null && _confirmOrderData.totalFee != null
                  ? _confirmOrderData.totalFee.toString()
                  : "0.0",
              _orderIds[0]);
        })).then((value) {
          Navigator.of(context).pop(true);
          Navigator.of(context).pop();
        });
      }
    }, params: params, isShowLoading: true);
  }

  _callAlipay(String payInfo) async {
    Map payResult = {};
    try {
      payResult = await tobias.aliPay(payInfo);
      print("<tobias> $payResult");
      if (payResult != null && payResult["resultStatus"] != null) {
        switch (payResult["resultStatus"].toString()) {
          case "9000":
            // 订单支付成功
            Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
              return new BuySuccessPage(
                  _confirmOrderData != null &&
                          _confirmOrderData.totalFee != null
                      ? _confirmOrderData.totalFee.toString()
                      : "0.0",
                  _orderIds[0]);
            })).then((value) {
              Navigator.of(context).pop(true);
              Navigator.of(context).pop();
            });
            break;
          case "6001":
            // 用户中途取消
            break;
          default:
            // 支付失败
            ToastUtil.showMessageToast(payResult["memo"]);
            break;
        }
      }
    } on Exception catch (e) {
      print("<tobias> $e");
    }
  }

  _newOrder(String addressId, bool needExpress, var couponIds,
      {var orderItemIds, int skuId, int quantity}) {
    Map<String, Object> params = {
      "coupon_ids": couponIds.join(","),
      "address_id": addressId,
      "need_express": needExpress,
    };
    if (orderItemIds != null && orderItemIds.length > 0) {
      params["order_item_ids"] = orderItemIds.join(",");
    } else {
      params["sku_id"] = skuId;
      params["quantity"] = quantity;
    }

    NetUtil.get(
      context,
      Api.ordersNew,
      (data, message) {
        ToastUtil.showMessageToast(message);

        if (!mounted) return;
        setState(() {
          _confirmOrderData = ConfirmOrderData.fromJson(data);
          _confirmOrderList = _confirmOrderData.orders;
        });
      },
      params: params,
    );
  }
}
